package cn.fl.ref.interestmanagement.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjfstpyinfo.service.IFncPrjFstpyInfoService;
import cn.fl.ref.fncprjpaysch.service.IFncPrjPaySchService;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPaySchDVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import cn.fl.ref.interestmanagement.service.IInterestManagementService;
import cn.fl.ref.interestmanagement.transfrom.InterestManagementVOTransform;
import cn.fl.ref.fncprjpaysch.vo.FncPrjPayRegVO;
import cn.fl.ref.interestmanagement.vo.InterestManagementVO;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.interestmanagement.condition.InterestmanagementQueryCondition;
import fl.ref.interestmanagement.dto.FncPrjPayRegInfoDTO;
import fl.ref.interestmanagement.dto.InterestManagementDTO;

@Controller
@RequestMapping("/interest/management")
public class InterestManagementController extends BaseController{

	private static final Logger logger = LoggerFactory.getLogger(InterestManagementController.class);
	
	@Autowired
	private IFriBaseInfoService friBaseInfoService;
	
	@Autowired
	private IFncPrjFstpyInfoService fncPrjFstpyInfoService;
	
	@Autowired
	private IInterestManagementService interestManagementService;
	
	@Autowired
	private IFncPrjPaySchService fncPrjPaySchService;
	
	/**
	 * 打开调息管理页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response){
		logger.info("加载调息管理列表页面.");
		ModelAndView view = new ModelAndView("rfbase/interestmanagementinfo/interestManagementInfoList");
		//获取融资机构
		FriBaseInfoQueryCondition condition = new FriBaseInfoQueryCondition();
		condition.setInsSts("1");
		List<FriBaseInfoVO> friBaseInfoVOs = friBaseInfoService.searchList(condition);
		List<KeyValueVO> fundRasInsNmList = fncPrjFstpyInfoService.transformToKeyValue(friBaseInfoVOs, FriBaseInfoVO.class.getName(), "id",
				"fundRasInsNm");
		view.addObject("fundRasInsNmList", fundRasInsNmList);
		view.addObject("frilist",JSON.toJSONString(friBaseInfoVOs));
		return view;
	}
	
	/**
	 * 初始化查询列表
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String fundRasInsCd = request.getParameter("fundRasInsCd");
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		
		InterestmanagementQueryCondition condition = new InterestmanagementQueryCondition();
		if(StringUtils.isNotEmpty(fundRasInsCd)){
			condition.setId(Long.valueOf(fundRasInsCd.trim()));
		}
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		page.setCondition(condition);
		
		Pager resultPager = this.interestManagementService.searchListPage(page);
		List<InterestManagementDTO> dtoList = (List<InterestManagementDTO>)resultPager.getResultList();
		List<InterestManagementVO> voList = InterestManagementVOTransform.toVOList(dtoList);
		ListPageVO<InterestManagementVO> listPage = new ListPageVO<InterestManagementVO>(voList,resultPager.getTotalCount());

		return listPage;
	}
	
	/**
	 * 查看还款表明细
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="viewRepaymentInfo.do", method = { RequestMethod.GET })
	public ModelAndView viewRepaymentInfo(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/interestmanagementinfo/fncPrjPaySchApply");
		String projId = request.getParameter("projId");
		String id = request.getParameter("id");
		Map<String,Object> map = fncPrjPaySchService.selectRepayProjInfo(Long.parseLong(projId));
		view.addObject("payschid", id);
		view.addObject("bscinfo", map);
		return view;
	}
	
	/**
	 * 加载还款明细列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/initDetlGrid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  initDetlGrid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("payschid");
		Long payschid = -1L;
		if(idTmp != null && !idTmp.equals("")){
			payschid = Long.parseLong(idTmp);
		}
		List<FncPrjPaySchDVO> payDLst = fncPrjPaySchService.selectRepayDetlLst(payschid);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", payDLst);
		map.put("Total", payDLst.size());
		return map;
	}
	
	/**
	 * 项目调息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="projectInterest.do", method = { RequestMethod.GET })
	public ModelAndView projectInterest(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbase/interestmanagementinfo/interestToProject");
		String projId = request.getParameter("projId");
		String regId = request.getParameter("regId");
		String id = request.getParameter("id");		//支付表id
		Map<String,Object> map = fncPrjPaySchService.selectRepayProjInfo(Long.parseLong(projId));
		//初始化支付调息表
		FncPrjPayRegInfoDTO regDto = new FncPrjPayRegInfoDTO();
		regDto.setPayId(Long.valueOf(id));
		if(StringUtils.isEmpty(regId) || regId.equals("null")){
			long mainId = this.interestManagementService.insertPayRegInfo(regDto);
			view.addObject("regId", mainId);
		}else{
			regDto.setPayId(Long.valueOf(id));
			regDto.setId(Long.valueOf(regId));
			this.interestManagementService.modifyPayRegInfo(regDto);
			view.addObject("regId", regId);
		}
		view.addObject("payschid", id);
		view.addObject("bscinfo", map);
		return view;
	}
	
	/**
	 * 查询还款明细列表
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/getDetlGrid.do" ,method = {RequestMethod.GET})
	public @ResponseBody Map<String, Object>  getDetlGrid(HttpServletRequest request, HttpServletResponse response) {
		String idTmp = request.getParameter("payschid");
		Long payschid = -1L;
		if(idTmp != null && !idTmp.equals("")){
			payschid = Long.parseLong(idTmp);
		}
		List<Map<String, Object>> payDList = fncPrjPaySchService.getRepayDetlList(payschid);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", payDList);
		map.put("Total", payDList.size());
		return map;
	}
	
	/**
	 * 根据支付ID查询支付调息信息
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getById.do" ,method = {RequestMethod.GET})
	public Object getById(HttpServletRequest request, HttpServletResponse response){
		String paySchId = request.getParameter("payschId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "获取成功!");
		try {
			if(StringUtils.isEmpty(paySchId)){
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"支付ID不能为空!");
			}
			InterestManagementVO interestVO = interestManagementService.getById(Long.valueOf(paySchId),CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd());
			result.setData(interestVO);
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取数据失败,支付ID[" + paySchId + "]." + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误!");
			BaseLogUtils.error(logger, "getById", "获取数据失败,支付ID[" + paySchId + "]." + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	@RequestMapping(value="/saveInterestInfo.do" ,method = {RequestMethod.POST})
	public @ResponseBody Map<String, Object> saveInterestInfo(@RequestBody Object formdata) throws ParseException{
		Map<String, Object> map = new HashMap<String, Object>();
		String result = "0";
		JSONObject object = new JSONObject();
		object = JSONObject.fromObject(formdata);
		JSONArray grid1 = object.getJSONArray("griddata1");
		JSONArray payschIdJSON = object.getJSONArray("interest");
		try {
			JSONObject gobj = payschIdJSON.getJSONObject(0);
			String payschId = gobj.getString("payschId");
			String thIntTm = gobj.getString("thIntTm");
			String thIntRat = gobj.getString("thIntRat");
			String intRatType = gobj.getString("intRatType");
			String regId = gobj.getString("regId");
			if(StringUtils.isEmpty(payschId) || StringUtils.isEmpty(thIntTm) || StringUtils.isEmpty(thIntRat) || StringUtils.isEmpty(intRatType)){
				map.put("result", "-1");
				return map;
			}
			List<FncPrjPaySchDVO> list = new ArrayList<FncPrjPaySchDVO>();
			for(int i = 0; i < grid1.size(); i++){
				JSONObject obj = grid1.getJSONObject(i);
				if(obj.has("PAYPD")){
					if(dateCompareToSize(obj.getString("PAYDT"),thIntTm)){
						//本金
						FncPrjPaySchDVO vo = new FncPrjPaySchDVO();
						vo.setPayPd(Integer.parseInt(obj.getString("PAYPD")));
						vo.setPaySchId(Long.valueOf(payschId));
						vo.setFeeAmt(new BigDecimal(obj.getString("PRINCIPAL") == null ? "0": obj.getString("PRINCIPAL")).multiply(new BigDecimal(100)));
						vo.setFeeClsCd(1);
						list.add(vo);
						//利息
						FncPrjPaySchDVO vo2 = new FncPrjPaySchDVO();
						vo2.setPayPd(Integer.parseInt(obj.getString("PAYPD")));
						vo2.setPaySchId(Long.valueOf(payschId));
						vo2.setFeeAmt(new BigDecimal(obj.getString("INTEREST") == null ? "0": obj.getString("INTEREST")).multiply(new BigDecimal(100)));
						vo2.setFeeClsCd(2);
						list.add(vo2);
						//超额抵押
						FncPrjPaySchDVO vo3 = new FncPrjPaySchDVO();
						vo3.setPayPd(Integer.parseInt(obj.getString("PAYPD")));
						vo3.setPaySchId(Long.valueOf(payschId));
						vo3.setFeeAmt(new BigDecimal(obj.getString("MORTGAGE") == null ? "0": obj.getString("MORTGAGE")).multiply(new BigDecimal(100)));
						vo3.setFeeClsCd(3);
						list.add(vo3);
						//其他费用
						FncPrjPaySchDVO vo4 = new FncPrjPaySchDVO();
						vo4.setPayPd(Integer.parseInt(obj.getString("PAYPD")));
						vo4.setPaySchId(Long.valueOf(payschId));
						vo4.setFeeAmt(new BigDecimal(obj.getString("OTHEREXPENSES") == null ? "0": obj.getString("OTHEREXPENSES")).multiply(new BigDecimal(100)));
						vo4.setFeeClsCd(5);
						list.add(vo4);
						//剩余本金
						FncPrjPaySchDVO vo5 = new FncPrjPaySchDVO();
						vo5.setPayPd(Integer.parseInt(obj.getString("PAYPD")));
						vo5.setPaySchId(Long.valueOf(payschId));
						vo5.setFeeAmt(new BigDecimal(obj.getString("RESIDUALPRINCIPAL") == null ? "0": obj.getString("RESIDUALPRINCIPAL")).multiply(new BigDecimal(100)));
						vo5.setFeeClsCd(6);
						list.add(vo5);
					}
				}else{
					continue;
				}
			}
			if(list != null && list.size()>0){
				//更新支付明细表信息
				fncPrjPaySchService.interestUpdateRepayDetl(list);
				//更新支付调息表
				FncPrjPayRegVO regVO = new FncPrjPayRegVO();
				regVO.setPreIntRate(new BigDecimal(thIntRat));
				regVO.setPreIntTm(DateUtils.formatStringToDate(thIntTm, DateUtils.YYYY_MM_DD));
				regVO.setPayId(Long.valueOf(payschId));
				regVO.setIntRatType(Integer.parseInt(intRatType));
				regVO.setId(Long.valueOf(regId));
				fncPrjPaySchService.modifyFncPrjPayReg(regVO);
			}else{
				result = "-1";
			}
		} catch (Exception e) {
			result = "-1";
			BaseLogUtils.error(logger, "-", "异常", e);
		}
		map.put("result", result);
		return map;
	}
	
	/**
	 * 日期比较大小
	 * @param date1
	 * @param date2
	 * @return
	 */
	private boolean dateCompareToSize(String date1, String date2){
		Date dt1 = new Date();
		dt1.setTime(Long.valueOf(date1));
		Date dte1 = DateUtils.formatDate(dt1, DateUtils.YYYY_MM_DDHHMMSS);
		Date dte2 = DateUtils.formatStringToDate(date2, DateUtils.YYYY_MM_DD);
		if(dte1.getTime() > dte2.getTime()){
			return true;
		}else{
			return false;
		}
	}
	
}
